package sk.fiit.icp.components.ajax;

import java.util.ArrayList;
import java.util.List;

import org.apache.wicket.markup.html.WebPage;
import org.apache.wicket.request.IRequestParameters;
import org.apache.wicket.request.cycle.RequestCycle;
import org.apache.wicket.request.handler.TextRequestHandler;
import org.apache.wicket.request.http.WebRequest;
import org.apache.wicket.request.mapper.parameter.PageParameters;
import org.apache.wicket.spring.injection.annot.SpringBean;
import org.joda.time.DateTime;
import org.json.JSONException;
import org.json.JSONObject;

import sk.fiit.icp.components.SignInSession;
import sk.fiit.icp.components.Utils;
import sk.fiit.icp.data.Events;
import sk.fiit.icp.data.EventsDao;
import sk.fiit.icp.data.UsersDao;

public class DataService extends WebPage {

	@SpringBean(name = "eventsDao")
	public EventsDao eventsDao;
	
	@SpringBean(name = "usersDao")
	public UsersDao usersDao;

	public DataService(PageParameters params) {

		if ( !params.isEmpty() ) {
			RequestCycle requestCycle = RequestCycle.get();

			requestCycle.scheduleRequestHandlerAfterCurrent( new TextRequestHandler( "application/json", "UTF-8", getJson( params.get(
					"method" ).toString() ) ) );
		}

	}

	private String getJson(String method) {

		final WebRequest wr = (WebRequest) getRequest();
		IRequestParameters requestParameters = wr.getRequestParameters();

		if ( "list".equals( method ) ) {
			return listCalendar();
		}
		if ( "remove".equals( method ) ) {
			return removeEvent( requestParameters.getParameterValue( "eventId" ).toInt() );
		}
		if ( "update".equals( method ) ) {
			return updateEvent( requestParameters.getParameterValue( "eventId" ).toInt(), requestParameters.getParameterValue( "startTime" )
					.toString(), requestParameters.getParameterValue( "endTime" ).toString() );
		}
		

		return null;
	}

	
	private String updateEvent(int eventId, String startTime, String endTime) {
		JSONObject json = new JSONObject();
		Events ev = eventsDao.findById( eventId );
		ev.setStartTime( Utils.JSDateStringToDate( startTime ) );
		ev.setEndTime( Utils.JSDateStringToDate( endTime ) );

		eventsDao.update( ev );

		try {
			json.put( "IsSuccess", true );
			json.put( "Msg", "Successful" );

		} catch ( JSONException e ) {
			try {
				json.put( "IsSuccess", false );
				json.put( "Msg", "Failed" );
			} catch ( JSONException e1 ) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
		}

		return json.toString();
	}

	private String removeEvent(int eventId) {
		JSONObject json = new JSONObject();
		int rc = eventsDao.remove( eventId );
		try {
			if ( rc == 0 ) {

				json.put( "IsSuccess", false );
				json.put( "Msg", "Error: No delete executed!" );
			} else if ( rc == 1 ) {
				json.put( "IsSuccess", true );
				json.put( "Msg", "Successful" );
			} else {
				json.put( "IsSuccess", false );
				json.put( "Msg", "Error : Too many deleted records!" );
			}
		} catch ( JSONException e ) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return json.toString();
	}

	private String listCalendar() {

		JSONObject json = new JSONObject();
		try {
			List<Events> events = eventsDao.findAllByUser( ((SignInSession) getSession()).getUser() );
			ArrayList<Object> event;
			for ( Events e : events ) {
				event = new ArrayList<Object>( 11 );
				event.add( e.getIdevent() ); // event ID
				event.add( e.getTitle() ); // title
				event.add( Utils.dateToJSString( e.getStartTime() ) ); // starttime
				event.add( Utils.dateToJSString( e.getEndTime() ) ); // endtime
				event.add( 0 ); // ?
				event.add( 0 ); // more than one day event
				event.add( 0 ); // recurring event
				event.add( 2 ); // ?
				event.add( 1 ); //
				event.add( e.getLocation() ); // location
				event.add( "" ); // attends

				json.append( "events", event );
			}

			DateTime date = new DateTime();

			json.put( "issort", true );
			json.put( "start", Utils.dateToJSString( date.minusDays( 2 ).withHourOfDay( 0 ).withMinuteOfHour( 0 ).toDate() ) );
			json.put( "end", Utils.dateToJSString( date.plusDays( 3 ).withHourOfDay( 23 ).withMinuteOfHour( 59 ).toDate() ) );
			json.put( "error", JSONObject.NULL );

		} catch ( JSONException e ) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return json.toString();
	}
}
